<template>
  <div class="container">
    <el-divider content-position="left"><span class="title-left-color">注册信息</span></el-divider>
    <div style="margin: 0 70px">
      <el-descriptions :column="2" size="default">
        <el-descriptions-item label="店铺名称:">{{ storeInfo.store_name }}</el-descriptions-item>
        <el-descriptions-item label="联系人:">{{ storeInfo.contacts_name }}</el-descriptions-item>
        <el-descriptions-item label="手机号:">{{ storeInfo.contacts_mobile }}</el-descriptions-item>
        <el-descriptions-item label="申请时间:">{{ storeInfo.add_time }}</el-descriptions-item>
        <el-descriptions-item label="所在地区:">{{ storeInfo.address }}</el-descriptions-item>
        <el-descriptions-item label="详细地址:">{{ storeInfo.company_address }}</el-descriptions-item>
        <el-descriptions-item label="营业执照名称:">{{ storeInfo.company_name }}</el-descriptions-item>
        <el-descriptions-item label="法人名称:">{{ storeInfo.legal_person }}</el-descriptions-item>
        <el-descriptions-item label="收款账号姓名:">{{ storeInfo.alipay_account_name }}</el-descriptions-item>
        <el-descriptions-item label="收款支付宝账号:">{{ storeInfo.alipay_account }}</el-descriptions-item>
        <el-descriptions-item label="统一社会信用代码:">{{ storeInfo.business_licence_number }}</el-descriptions-item>
      </el-descriptions>
      <el-descriptions :column="2" size="default">
        <el-descriptions-item label="营业执照:">
          <el-image style="width: 130px; height: 130px" :src="storeInfo.business_licence_cert" :preview-src-list="[storeInfo.business_licence_cert]"></el-image>
        </el-descriptions-item>
        <el-descriptions-item label="门头照:">
          <el-image style="width: 130px; height: 130px" :src="storeInfo.door_phone" :preview-src-list="[storeInfo.door_phone]"></el-image>
        </el-descriptions-item>
      </el-descriptions>
    </div>
    <el-form ref="formRef" :model="form" :rules="rules" v-loading="loading" label-width="150px">
      <el-divider content-position="left"><span class="title-left-color">操作</span></el-divider>
      <el-row :gutter="10">
        <el-col :span="12">
          <el-form-item label="配件业务员：" prop="staff_uid">
            <el-select v-model.trim="form.staff_uid" placeholder="请选择配件业务员" clearable class="">
              <el-option v-for="item in storageList" :label="item.username" :value="item.user_id" :key="item.id"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="租机业务员：" prop="rent_staff_uid">
            <el-select v-model.trim="form.rent_staff_uid" placeholder="请选择租机业务员" clearable class="">
              <el-option v-for="item in rentSalesmanList" :label="item.username" :value="item.user_id" :key="item.id"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="店铺审核：" prop="apply_state">
            <el-select v-model.trim="form.apply_state" placeholder="请选择店铺审核情况" clearable class="">
              <el-option v-for="item in applyType" :label="item.dictLabel" :value="item.dictValue" :key="item.id"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="10">
        <el-col :span="12">
          <el-form-item label="备注：" prop="review_msg">
            <el-input v-model.trim="form.review_msg" type="textarea" :rows="2" placeholder="备注"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-divider content-position="left"><span class="title-left-color">门店情况</span></el-divider>
      <el-row :gutter="10">
        <el-col :span="12">
          <el-form-item label="人员规模：" prop="personnel_size">
            <el-input v-model.trim="form.store_info.personnel_size" placeholder="请填写人员规模"><template #append>人</template></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="老板年龄：" prop="boss_age">
            <el-input v-model.trim="form.store_info.boss_age" placeholder="请填写老板年龄"><template #append>岁</template></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="正常购买数量：" prop="purchase_quantity">
            <el-input v-model.trim="form.store_info.purchase_quantity" placeholder="请填写正常购买数量"><template #append>台</template></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="店铺等级：" prop="shop_level">
            <el-select v-model.trim="form.store_info.shop_level" placeholder="请选择店铺等级" clearable>
              <el-option v-for="item in shopLevelList" :label="item.dictLabel" :value="item.dictValue" :key="item.id"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="主营业务：" prop="main_business">
            <el-select v-model.trim="form.store_info.main_business" multiple placeholder="请选择主营业务" clearable>
              <el-option v-for="item in mainBusinessList" :label="item.dictLabel" :value="item.dictValue" :key="item.id"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="线上推广：" prop="online_promotion">
            <el-select v-model.trim="form.store_info.online_promotion" multiple placeholder="请选择线上推广" clearable>
              <el-option v-for="item in onlinePromotionList" :label="item.dictLabel" :value="item.dictValue" :key="item.id"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="入驻形式：" prop="form_of_entry">
            <el-select v-model.trim="form.store_info.form_of_entry" placeholder="请选择入驻形式" clearable>
              <el-option v-for="item in formOfEntryList" :label="item.dictLabel" :value="item.dictValue" :key="item.id"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="入驻兴趣点：" prop="settle_in_interest_points">
            <el-select v-model.trim="form.store_info.settle_in_interest_points" multiple placeholder="请选择入驻兴趣点" clearable>
              <el-option v-for="item in settleInInterestPointsList" :label="item.dictLabel" :value="item.dictValue" :key="item.id"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="经营时间：">
            <el-input v-model.trim="form.store_info.operating_hours" placeholder="请填写经营时间"><template #append>年</template></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="门店手机数量：">
            <el-input v-model.trim="form.store_info.store_mobile_number" placeholder="请填写门店手机数量"><template #append>台</template></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="分期销量：">
            <el-input v-model.trim="form.store_info.installment_sales_volume" placeholder="请填写分期销量"><template #append>台</template></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="获客渠道：">
            <el-select v-model.trim="form.store_info.customer_acquisition_channel" multiple placeholder="请选择获客渠道" clearable>
              <el-option v-for="item in customerAcquisitionChannelList" :label="item.dictLabel" :value="item.dictValue" :key="item.id"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="物料：">
            <el-select v-model.trim="form.store_info.materials" multiple placeholder="请选择物料" clearable>
              <el-option v-for="item in materialsList" :label="item.dictLabel" :value="item.dictValue" :key="item.id"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="客户动作：">
            <el-select v-model.trim="form.store_info.customer_action" multiple placeholder="请选择客户动作" clearable>
              <el-option v-for="item in customerActionList" :label="item.dictLabel" :value="item.dictValue" :key="item.id"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <div class="footer-center">
      <el-button :disabled="disabledbtn" @click="cancelSubmit">取 消</el-button>
      <el-button type="primary" :disabled="disabledbtn" v-if="!isDisabledbtn" @click="submitForm">确 定</el-button>
    </div>
  </div>
</template>

<script setup lang="ts">
import { IMG_URL } from "@/utils/config";
import type { postOrPutType } from "@/constants";
import type { HasId, ViewMode } from "@/types/common";
import { useState } from "@/hooks/useState.ts";
import type { IRegisterStoreDetailDTO, IRegisterStoreDetailVO, IRegisterStoreInfoVO } from "@/types/storeManager/registerStore";
import type { IDictData } from "@/types/dict";
import type { IRentStaff } from "@/types/staff/rentStaff";
import type { IStaff } from "@/types/staff/staff";
import { useDictData } from "@/hooks/network/useDictData";
import { commonStoreApplyInfo, getStoreApplyByIdInfo } from "@/utils/api/storeApply";
import { handleVerifyFormatDate, splitAndFilter } from "@/utils/utils";
const { disabledbtn, loading, toggleState } = useState();
const { getDictData } = useDictData();
interface Props {
  id: number;
  applyType: Array<IDictData>;
  storageList: Array<IStaff>;
  rentSalesmanList: Array<IRentStaff>;
}
const { id, applyType, storageList, rentSalesmanList } = defineProps<Props>();
const formStatus = defineModel<ViewMode>("formStatus", { required: true });

const emit = defineEmits<{
  handleInitData: [];
  handleSuccess: [];
}>();
const isDisabledbtn = ref(false);
const checkAll = ref(false);
const formRef = useTemplateRef("formRef");
const methodType = ref<postOrPutType>("PUT");
const personnelSizeList = ref<Array<IDictData>>([]); /* 人员规模 */
const bossAgeList = ref<Array<IDictData>>([]); /* 老板年龄 */
const purchaseQuantityList = ref<Array<IDictData>>([]); /* 正常购买数量 */
const shopLevelList = ref<Array<IDictData>>([]); /* 店铺等级 */
const mainBusinessList = ref<Array<IDictData>>([]); /* 主营业务 */
const onlinePromotionList = ref<Array<IDictData>>([]); /* 线上推广 */
const formOfEntryList = ref<Array<IDictData>>([]); /* 入驻形式 */
const settleInInterestPointsList = ref<Array<IDictData>>([]); /* 入驻兴趣点 */
const operatingHoursList = ref<Array<IDictData>>([]); /* 经营时间 */
const storeMobileNumberList = ref<Array<IDictData>>([]); /* 门店手机数量 */
const installmentSalesVolumeList = ref<Array<IDictData>>([]); /* 分期销量 */
const customerAcquisitionChannelList = ref<Array<IDictData>>([]); /* 获客渠道 */
const materialsList = ref<Array<IDictData>>([]); /* 物料 */
const customerActionList = ref<Array<IDictData>>([]); /* 客户动作 */

const storeInfo = reactive<IRegisterStoreInfoVO>({
  store_name: "",
  contacts_name: "",
  contacts_mobile: "",
  add_time: "",
  address: "",
  company_address: "",
  business_licence_cert: "",
  door_phone: "",
  company_name: "",
  legal_person: "",
  alipay_account_name: "",
  alipay_account: "",
  business_licence_number: ""
});
const form = reactive<IRegisterStoreDetailDTO>({
  id: 0,
  staff_uid: "",
  rent_staff_uid: "",
  review_msg: "",
  apply_state: "",
  store_info: {
    id: 0,
    store_apply_id: 0,
    form_of_entry: "",
    settle_in_interest_points: [],
    personnel_size: "",
    operating_hours: "",
    store_mobile_number: "",
    boss_age: "",
    purchase_quantity: "",
    installment_sales_volume: "",
    customer_acquisition_channel: [],
    shop_level: "",
    materials: [],
    main_business: [],
    customer_action: [],
    online_promotion: []
  }
});
const rules = reactive({
  status: [{ required: true, message: "请选择店铺申请类型", trigger: "blur" }],
  staff_uid: [{ required: true, message: "请选择配件业务员", trigger: "blur" }],
  rent_staff_uid: [{ required: true, message: "请选择租机业务员", trigger: "blur" }]
});

/* formStatus处理器 */
const statusHandlers: Record<ViewMode, () => void> = {
  view: () => {
    isDisabledbtn.value = true;
  },
  edit: () => {
    methodType.value = "PUT";
  },
  add: () => {
    methodType.value = "POST";
  },
  none: () => {
    /* 初始化数据 */
    handleInitData();
  }
};
/* 监听formStatus,新增，编辑，查看的时候都可以打开模态框，又是有不同的操作和效果，需要单独判断，none为模态框关闭的情况，需要初始化数据 */
watch(formStatus, newValue => {
  const handler = statusHandlers[newValue];
  handler?.();
});
/*  */
watch(
  () => id,
  newValue => {
    if (newValue == 0) {
      /* 初始化数据 */
      handleInitData();
    } else {
      form.id = newValue;
      handleGetStoreApplyByIdInfo(id);
    }
  }
);

/* 获取注册店铺详情信息 */
function handleGetStoreApplyByIdInfo(id: number) {
  toggleState(true);
  getStoreApplyByIdInfo<IRegisterStoreDetailVO, HasId>({ id })
    .then(res => {
      form.id = res.result.id;
      storeInfo.store_name = res.result.store_name;
      storeInfo.contacts_name = res.result.contacts_name;
      storeInfo.contacts_mobile = res.result.contacts_mobile;
      storeInfo.address = `${res.result.company_province}-${res.result.company_city}-${res.result.company_district}`;
      storeInfo.company_address = res.result.company_address;
      storeInfo.add_time = handleVerifyFormatDate(res.result.add_time);
      storeInfo.business_licence_cert = IMG_URL + res.result.business_licence_cert;
      storeInfo.door_phone = IMG_URL + res.result.door_phone;

      storeInfo.company_name = res.result.company_name;
      storeInfo.legal_person = res.result.legal_person;
      storeInfo.alipay_account_name = res.result.alipay_account_name;
      storeInfo.alipay_account = res.result.alipay_account;
      storeInfo.business_licence_number = res.result.business_licence_number;
      form.staff_uid = res.result.staff_uid === 0 ? "" : res.result.staff_uid;
      form.rent_staff_uid = res.result.rent_staff_uid === 0 ? "" : res.result.rent_staff_uid;
      form.review_msg = res.result.review_msg;
      form.apply_state = String(res.result.apply_state);

      if (res.result.store_info !== null) {
        form.store_info.id = res.result.store_info.id;
        form.store_info.form_of_entry = res.result.store_info.form_of_entry;
        form.store_info.settle_in_interest_points = splitAndFilter(res.result.store_info.settle_in_interest_points);
        form.store_info.personnel_size = res.result.store_info.personnel_size;
        form.store_info.operating_hours = res.result.store_info.operating_hours;
        form.store_info.store_mobile_number = res.result.store_info.store_mobile_number;
        form.store_info.boss_age = res.result.store_info.boss_age;
        form.store_info.purchase_quantity = res.result.store_info.purchase_quantity;
        form.store_info.installment_sales_volume = res.result.store_info.installment_sales_volume;
        form.store_info.customer_acquisition_channel = splitAndFilter(res.result.store_info.customer_acquisition_channel);

        form.store_info.shop_level = res.result.store_info.shop_level;
        form.store_info.materials = splitAndFilter(res.result.store_info.materials);
        form.store_info.main_business = splitAndFilter(res.result.store_info.main_business);
        form.store_info.customer_action = splitAndFilter(res.result.store_info.customer_action);
        form.store_info.online_promotion = splitAndFilter(res.result.store_info.online_promotion);
      }
    })
    .catch(() => {})
    .finally(() => {
      toggleState(false);
    });
}
/* 初始化数据 */
function handleInitData() {
  methodType.value = "POST";
  isDisabledbtn.value = false;

  checkAll.value = false;

  form.id = 0;
  form.staff_uid = "";
  form.rent_staff_uid = "";
  form.review_msg = "";
  form.apply_state = "";

  form.store_info.id = 0;
  form.store_info.form_of_entry = "";
  form.store_info.settle_in_interest_points = [];
  form.store_info.personnel_size = "";
  form.store_info.operating_hours = "";
  form.store_info.store_mobile_number = "";
  form.store_info.boss_age = "";
  form.store_info.purchase_quantity = "";
  form.store_info.installment_sales_volume = "";
  form.store_info.customer_acquisition_channel = [];
  form.store_info.shop_level = "";
  form.store_info.materials = [];
  form.store_info.main_business = [];
  form.store_info.customer_action = [];
  form.store_info.online_promotion = [];

  storeInfo.store_name = "";
  storeInfo.contacts_name = "";
  storeInfo.contacts_mobile = "";
  storeInfo.add_time = "";
  storeInfo.address = "";
  storeInfo.company_address = "";
  storeInfo.business_licence_cert = "";
  storeInfo.door_phone = "";
  storeInfo.company_name = "";
  storeInfo.legal_person = "";
  storeInfo.alipay_account_name = "";
  storeInfo.alipay_account = "";
  storeInfo.business_licence_number = "";

  formRef.value?.resetFields();
  formRef.value?.clearValidate();
}

/* 保存校验数据 */
function handleValidate() {
  return true;
}

/* 保存或编辑 */
function submitForm() {
  if (!formRef.value) return;
  formRef.value.validate(valid => {
    if (!valid) {
      ElMessage.warning("请填写必填字段");
      return;
    }
    if (!handleValidate()) return;
    submitFormInfo();
  });
}

/* 保存或编辑信息 */
function submitFormInfo() {
  /* 防止多次提交 */
  toggleState(true);
  commonStoreApplyInfo(form, methodType.value)
    .then(res => {
      ElMessage.success(res.msg);
      cancelSubmit();
      emit("handleSuccess");
    })
    .catch(() => {})
    .finally(() => {
      toggleState(false);
    });
}
/* 保存或编辑 取消提交 */
function cancelSubmit() {
  // clearData();
  // activeName = "one";
  emit("handleInitData");
}

getDictData("PERSONNEL_SIZE", personnelSizeList);
getDictData("BOSS_AGE", bossAgeList);
getDictData("PURCHASE_QUANTITY", purchaseQuantityList);
getDictData("SHOP_LEVEL", shopLevelList);
getDictData("MAIN_BUSINESS", mainBusinessList);
getDictData("ONLINE_PROMOTION", onlinePromotionList);
getDictData("FORM_OF_ENTRY", formOfEntryList);
getDictData("SETTLE_IN_INTEREST_POINTS", settleInInterestPointsList);
getDictData("OPERATING_HOURS", operatingHoursList);
getDictData("STORE_MOBILE_NUMBER", storeMobileNumberList);
getDictData("INSTALLMENT_SALES_VOLUME", installmentSalesVolumeList);
getDictData("CUSTOMER_ACQUISITION_CHANNEL", customerAcquisitionChannelList);
getDictData("MATERIALS", materialsList);
getDictData("CUSTOMER_ACTION", customerActionList);
</script>

<style lang="scss" scoped>
/* 修改select的盒模型 */
.el-select {
  display: block;
}
/* 底部按钮居中 */
.footer-center {
  margin: 10px 0;
  text-align: center;
}
</style>
